<?php

namespace App\Http\Controllers;

use App\Models\AlipayDataResource;
use App\Models\DataResource;
use App\Models\Device;
use Illuminate\Support\Facades\Cache;
use zgldh\QiniuStorage\QiniuStorage;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Validator;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Log;
use DB;
use Exception;
use Carbon\Carbon;
use App\Models\DeviceDetailedList;

class Controller extends BaseController
{
  use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

  protected static function success($code = 0, $message = '', $data = null)
  {
    $result = array(
      'code' => $code,
      'message' => $message ? $message : '操作成功',
      'data' => $data ? $data : null
    );
    return response()->json($result, 200, [], JSON_UNESCAPED_UNICODE);
  }

  /**
   * @param $errors 数据可以为字符串，字符数组
   * @return json
   */
  protected static function failure($code, $message)
  {
    $result = array(
      'code' => $code,
      'message' => $message ? $message : '操作失败',
      'data' => null,
    );
    return response()->json($result, 200, [], JSON_UNESCAPED_UNICODE);
  }

  protected function uploadCompressImg($base64_img)
  {
    $base64 = preg_replace("/\s/", '+', $base64_img);
    $img = base64_decode($base64);
    $disk = QiniuStorage::disk('qiniu');
    $img_name = date('Y/m/d-H:i:s-') . uniqid() . '.png';
    $filename = $disk->put($img_name, $img);//上传
    if (!$filename) {
      return false;
    }
    $img_url = $disk->privateDownloadUrl($img_name); //获取下载链接
    $data['image_name'] = $img_name;
    $data['img_url'] = $img_url;
    return $data;
  }

  protected function deleteImgFromQiniu($img_name)
  {
    $disk = QiniuStorage::disk('qiniu');
    $rs = $disk->delete($img_name);
    return $rs;
  }

  public function deleteFromUploads($path)
  {
    $rs = \File::delete($path);
    return $rs;
  }

  //aua自定义
    protected function deviceDetailedList($type,$detail_type,$device_id=null)
    {
        if(!$device_id) return;
        if($type == 1){
            $count = 'request_count';
        }else $count = 'detail_count';
        $query = DeviceDetailedList::where('created_at','>=', date('Y-m-d'))
            ->where('device_id',$device_id)
            ->where('detail_type',$detail_type)
            ->first();
        if(!$query){
            try{
                $device_code = Device::where('id',$device_id)->select('device_code')->first()->device_code;
            }catch (Exception $e){
                $device_code = '';
            }
            $query = DeviceDetailedList::create([
                'device_id' => $device_id,
                'detail_type' => $detail_type,
                'request_count' => 0,
                'detail_count'  => 0,
                'device_code'  => $device_code,
            ]);
        }
        $query->$count += 1;
        $query->save();
        return $query->$count;
    }

    public function finishConfluenceTask(Request $request)//除task执行完成接口总汇
    {
        $validator = Validator::make($request->all(), [//1发朋友圈，2查支付宝，3查微信，4完成任务
            'device_id' => 'required|exists:devices,id',
            'task_id' => 'required|exists:tasks,id',
            'sns_id' => 'sometimes|required|exists:sns,id'
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $return = null;
        switch ($request->task_id){
            //case 1: $detail_type = ?; break;//加粉已单独作另一个数据，此接口闲置
            case 2: $detail_type = 1;//发朋友圈
                if(!$request->sns_id) return $this->failure(-1, '缺少 sns_id');
                $return = SnsController::postedDevice($request);
                break;
            case 3: $detail_type = 2; break;//查支付宝(fans)
            case 4: $detail_type = 8; break;//检测微信(data resources)
            case 5: $detail_type = 3; break;//设备行为模拟操作
            default: return $this->failure(-1, 'task_id error');
        }
        $count = $this->deviceDetailedList($type=2,$detail_type,$request->device_id);
        if($return) return $return;
        return $this->success(0, '请求成功', $count);
    }

    public function finishConfluence(Request $request)//除task外的执行完成接口总汇
    {
        $validator = Validator::make($request->all(), [
            'device_id' => 'required|exists:devices,id',
            'detail_type' => 'required',
        ]);
        if ($validator->fails()) {
            return $this->failure(-1, $validator->errors()->first());
        }
        $count = $this->deviceDetailedList($type=2,$request->detail_type,$request->device_id);
        return $this->success(0, '请求成功', $count);
    }

    public function detailIndex(Request $request)
    {
        $perPage = $request->perpage ? $request->perpage : 100;
        $perPage = !is_numeric($perPage) ? 99999 : $perPage;
        $created_at = $request->created_at ? Carbon::parse($request->created_at) : Carbon::today();
        $detail = DeviceDetailedList::where('device_code','like','%'. $request->device_code .'%')
            ->where(DB::raw('date(created_at)'), $created_at);
        switch ($request->rank){
            case 1:
                $detail = $detail->where('detail_type',8)->orderBy('detail_count','desc')->select('device_id','device_code');
                break;
            default:
                $detail = Device::select('id','device_code')->where('device_code','like','%'. $request->device_code .'%');
        }
        $detail = $detail->paginate($perPage)->toArray();
        $data = [];
        foreach ($detail['data'] as $list){
            try{
                $row['detail'] = DeviceDetailedList::where('device_id',$list['device_id'])
                    ->where(DB::raw('date(created_at)'), $created_at)
                    ->get();
            }catch (Exception $e){
                $row['detail'] = DeviceDetailedList::where('device_id',$list['id'])
                    ->where(DB::raw('date(created_at)'), $created_at)
                    ->get();
            }
            $row['device_code'] = $list['device_code'];
            array_push($data,$row);
        }
        $detail['data'] = $data;
        return $this->success(0,'获取成功',$detail);

    }
    public function run()
    {
        $detail = DeviceDetailedList::where('device_code','')->get();
        foreach ($detail as $list){
            try{
                $list->device_code = Device::where('id',$list->device_id)->select('device_code')->first()->device_code;
            }catch (Exception $e){
                $list->device_code = '';
            }
            $list->save();
        }
        return 'ok';
    }

    public function pinCheck(Request $request){
      if($request->pin == '98k'){
          session(['pin'=>str_random(10)]);
          Cache::add('pin'.session('pin'),session('pin'),1);
          return $this->success(0,session('pin'));
      }
      return $this->failure(-1,'pin error');
    }
}
